package com.mz.mattress.admin.interceptor;

import com.mz.mattress.admin.common.FailMessage;
import com.mz.mattress.admin.common.Holder;
import com.mz.mattress.api.common.Constants;
import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.common.ServiceException;
import com.mz.mattress.api.enums.FailCodeEnum;
import com.mz.mattress.api.jwt.AdminJwt;
import com.mz.mattress.api.jwt.JwtTokenUtil;
import com.mz.mattress.api.util.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        String token = request.getHeader(Constants.LOGIN_TOKEN_KEY);
        if (token == null || token.isEmpty()) {
            throw new ServiceException(FailCodeEnum.ACCOUNT_NOT_LOGIN);
        }

        AdminJwt adminJwt = JwtTokenUtil.parseAdminToken(token);
        if (adminJwt == null) {
            throw new ServiceException(FailCodeEnum.ACCOUNT_NOT_LOGIN);
        }

        String json = JacksonUtils.toJson(adminJwt);
        log.info("token_admin_json={}", json);

//        //  校验token来源
//        if (!StrUtil.equals(ClientEnum.ADMIN.name(), userJwt.getClientId())) {
//            log.error("error_client_id, userJwt:{}", userJwt);
//            throw new ServiceException(FailCodeEnum.ACCOUNT_NOT_LOGIN);
//        }
//
        log.info("token_admin,userId={},userName={}", adminJwt.getUserId(), adminJwt.getUsername());

        // 放入值
        Holder.ADMIN_JWT_THREAD_LOCAL.set(adminJwt);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        //移除值
        Holder.ADMIN_JWT_THREAD_LOCAL.remove();
    }

    public static void main(String[] args) {
        System.out.println(JacksonUtils.toJson(Result.fail(FailMessage.UNLOGIN)));
    }
}
